/**
 * @param {number[]} nums
 * @param {number} target
 * @return {number[][]}
 */
var fourSum = function (nums, target) {
    nums.sort((x, y) => x - y)
    let res = []
    let len = nums.length
    for (let i = 0; i < len - 3; i++) {
        if (i > 0 && nums[i] === nums[i - 1]) {
            continue
        }
        for (let j = i + 1; j < len - 2; j++) {
            if (j > i + 1 && nums[j] === nums[j - 1]) {
                continue
            }
            let sum1 = nums[i] + nums[j]
            // if (sum1 > target && (sum1 > 0 || target > 0)) {
            //     return res
            // }
            let left = j + 1
            let right = len - 1
            while (left < right) {
                let sum2 = sum1 + nums[left] + nums[right]
                if (sum2 > target) {
                    right--
                } else if (sum2 < target) {
                    left++
                } else {
                    res.push([nums[i], nums[j], nums[left], nums[right]])
                    while (left < right && nums[left] === nums[left + 1]) {
                        left++
                    }
                    while (left < right && nums[right] === nums[right - 1]) {
                        right--
                    }
                    left++
                    right--
                }
            }
        }

    }
    return res
};

// let nums = [2,2,2,2,2]
let nums = [1,0,-1,0,-2,2]
console.log(fourSum(nums, 0))